package com.xindacloud.sms.adapter.service.business.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xindacloud.sms.adapter.dao.SmsSubmissionRecordMapper;
import com.xindacloud.sms.adapter.dto.SearchMessageDTO;
import com.xindacloud.sms.adapter.entity.SmsProjectMember;
import com.xindacloud.sms.adapter.entity.SmsSubmissionRecord;
import com.xindacloud.sms.adapter.exception.ServiceException;
import com.xindacloud.sms.adapter.service.business.ISmsProjectMemberService;
import com.xindacloud.sms.adapter.service.business.ISmsSubmissionRecordService;
import com.xindacloud.sms.adapter.service.business.ISmsUserAllowOperatorService;
import com.xindacloud.sms.adapter.service.business.ISmsUserService;
import com.xindacloud.sms.adapter.utils.UnionResultHelp;
import com.xindacloud.sms.adapter.vo.SearchMessageVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class SmsSubmissionRecordServiceImpl extends ServiceImpl<SmsSubmissionRecordMapper, SmsSubmissionRecord> implements ISmsSubmissionRecordService {

    @Autowired
    ISmsProjectMemberService projectMemberService;

    @Autowired
    ISmsUserAllowOperatorService smsUserAllowOperatorService;
    @Autowired
    ISmsUserService smsUserService;

    @Override
    public boolean insertBatch(Collection<SmsSubmissionRecord> entityList) {
        return saveBatch(entityList);
    }

    @Override
    public boolean updateStatusForDLR(SmsSubmissionRecord smsSubmissionRecord) {
        return lambdaUpdate()
                .set(SmsSubmissionRecord::getFinalStatus, smsSubmissionRecord.getFinalStatus())
                .set(StringUtils.isNotEmpty(smsSubmissionRecord.getNetwork()), SmsSubmissionRecord::getNetwork, smsSubmissionRecord.getNetwork())
                .set(StringUtils.isNotEmpty(smsSubmissionRecord.getErrorText()), SmsSubmissionRecord::getErrorText, smsSubmissionRecord.getErrorText())
                .set(Objects.nonNull(smsSubmissionRecord.getFree()), SmsSubmissionRecord::getFree, smsSubmissionRecord.getFree())
                .set(SmsSubmissionRecord::isMinus, true)
                .set(StringUtils.isNotEmpty(smsSubmissionRecord.getAgentId()), SmsSubmissionRecord::getAgentId, smsSubmissionRecord.getAgentId())
                .set(SmsSubmissionRecord::getMessageTimestamp, LocalDateTime.now())
                .eq(SmsSubmissionRecord::getSendTo, smsSubmissionRecord.getSendTo())
                .eq(SmsSubmissionRecord::getMessageId, smsSubmissionRecord.getMessageId())
                .update();

    }

    @Override
    public SmsSubmissionRecord queryOneSubmissionRecordFor(String sendTo, String messageId) {
        try {
            return lambdaQuery()
                    .eq(SmsSubmissionRecord::getSendTo, sendTo)
                    .eq(SmsSubmissionRecord::getMessageId, messageId)
                    .one();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public SmsSubmissionRecord queryOneSubmissionRecordByMessageId(String messageId) {
        try {
            return lambdaQuery()
                    .eq(SmsSubmissionRecord::getMessageId, messageId)
                    .one();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public List<SmsSubmissionRecord> querySmsSubmissionRecordByTaskId(String taskId) {
        try {
            return lambdaQuery().eq(SmsSubmissionRecord::getTaskId, taskId).list();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public IPage<SearchMessageVO> searchMessage(SearchMessageDTO searchMessageDTO) {

        final int userId;
        try {
            userId = Integer.parseInt(searchMessageDTO.getUserId());
        } catch (NumberFormatException e) {
            throw new ServiceException("无效的用户ID", UnionResultHelp.StatusEnum.ParamsFail.code());
        }
        final List<SmsProjectMember> projectMembers = projectMemberService.queryProjectMemberInfoById(userId);
        if (CollectionUtils.isEmpty(projectMembers)) {
            return new Page<>();
        }
       /* List<String> projectIds = projectMembers.stream()
                .map(SmsProjectMember::getProjectId)
                .collect(toList());*/

        final IPage<SmsSubmissionRecord> smsSubmissionRecordIPage = lambdaQuery()
                .in(CollectionUtils.isNotEmpty(searchMessageDTO.getMessageIds()),
                        SmsSubmissionRecord::getMessageId, searchMessageDTO.getMessageIds())
                /*   .in(CollectionUtils.isNotEmpty(projectIds),
                           SmsSubmissionRecord::getProjectId, projectIds)*/
                .or(StringUtils.isNotEmpty(searchMessageDTO.getTo()), queryWrapper ->
                        queryWrapper.eq(SmsSubmissionRecord::getSendTo, searchMessageDTO.getTo()))
                .or(StringUtils.isNotEmpty(searchMessageDTO.getTo()), queryWrapper ->
                        queryWrapper.eq(SmsSubmissionRecord::getSendTo, "00".concat(searchMessageDTO.getTo())))
                .eq(StringUtils.isNotEmpty(searchMessageDTO.getAgentId()),
                        SmsSubmissionRecord::getAgentId, searchMessageDTO.getAgentId())

                .ge(StringUtils.isNotEmpty(searchMessageDTO.getStartDate()), SmsSubmissionRecord::getSubmitTime,
                        searchMessageDTO.getStartDate().concat(" ").concat("00:00:00"))
                .le(StringUtils.isNotEmpty(searchMessageDTO.getEndDate()), SmsSubmissionRecord::getSubmitTime,
                        searchMessageDTO.getEndDate().concat(" ").concat("23:59:59"))
                .orderByDesc(SmsSubmissionRecord::getSubmitTime)
                .page(new Page<>(searchMessageDTO.getCurrentPage(), searchMessageDTO.getPageSize()));

        return smsSubmissionRecordIPage.convert(smsSubmissionRecord -> {
            SearchMessageVO searchMessageVO = new SearchMessageVO();
            BeanUtils.copyProperties(smsSubmissionRecord, searchMessageVO);
            return searchMessageVO;
        });

    }


    @Override
    public boolean updateSmsSubmissionRecordFor(SmsSubmissionRecord smsSubmissionRecord) {
        return lambdaUpdate()
                .set(StringUtils.isNotEmpty(smsSubmissionRecord.getFinalStatus()),
                        SmsSubmissionRecord::getFinalStatus, smsSubmissionRecord.getFinalStatus())
                .set(StringUtils.isNotEmpty(smsSubmissionRecord.getNetwork()),
                        SmsSubmissionRecord::getNetwork, smsSubmissionRecord.getNetwork())
                .set(StringUtils.isNotEmpty(smsSubmissionRecord.getCountryCode()),
                        SmsSubmissionRecord::getCountryCode, smsSubmissionRecord.getCountryCode())
                .set(StringUtils.isNotEmpty(smsSubmissionRecord.getPrefix()),
                        SmsSubmissionRecord::getPrefix, smsSubmissionRecord.getPrefix())
                .set(Objects.nonNull(smsSubmissionRecord.getFree()),
                        SmsSubmissionRecord::getFree, smsSubmissionRecord.getFree())
                .set(Objects.nonNull(smsSubmissionRecord.getCostPrice()),
                        SmsSubmissionRecord::getCostPrice, smsSubmissionRecord.getCostPrice())
                .set(StringUtils.isNotEmpty(smsSubmissionRecord.getAgentId()),
                        SmsSubmissionRecord::getAgentId, smsSubmissionRecord.getAgentId())
                .set(StringUtils.isNotEmpty(smsSubmissionRecord.getSendFrom()),
                        SmsSubmissionRecord::getSendFrom, smsSubmissionRecord.getSendFrom())
                .set(StringUtils.isNotEmpty(smsSubmissionRecord.getMessageId()),
                        SmsSubmissionRecord::getMessageId, smsSubmissionRecord.getMessageId())
                .set(Objects.nonNull(smsSubmissionRecord.getSubmitStatusCode()),
                        SmsSubmissionRecord::getSubmitStatusCode, smsSubmissionRecord.getSubmitStatusCode())
                .set(StringUtils.isNotEmpty(smsSubmissionRecord.getErrorText()),
                        SmsSubmissionRecord::getErrorText, smsSubmissionRecord.getErrorText())
                .set(Objects.nonNull(smsSubmissionRecord.getMessageCount()),
                        SmsSubmissionRecord::getMessageCount, smsSubmissionRecord.getMessageCount())
                .eq(SmsSubmissionRecord::getSendTo, smsSubmissionRecord.getSendTo())
                .eq(SmsSubmissionRecord::getTaskId, smsSubmissionRecord.getTaskId())
                .eq(SmsSubmissionRecord::getUserId, smsSubmissionRecord.getUserId())
                .update();
    }

    @Override
    public SmsSubmissionRecord querySmsSubmissionRecord(SmsSubmissionRecord smsSubmissionRecord) {
        return lambdaQuery()
                .eq(SmsSubmissionRecord::getSendTo, smsSubmissionRecord.getSendTo())
                .eq(SmsSubmissionRecord::getTaskId, smsSubmissionRecord.getTaskId())
                .eq(SmsSubmissionRecord::getUserId, smsSubmissionRecord.getUserId())
                .one();
    }
}
